import React, { useEffect, useState } from 'react';
import './Comments.css';
import commentApi from '@/apis/commentApi';
import { useLocation } from 'react-router-dom';
import { Image, List, Rate, Toast } from 'react-vant';
import CommentComponent from '@/components/UserComment';
import { useAppSelector } from '@/hooks/storeHooks';

const limit = 10;

const Comments: React.FC = () => {
  const [comments, setComments] = useState<ResponseCommentsDto[]>([]);
  const [page, setPage] = useState<number>(1);
  const [finish, setFinish] = useState<boolean>(false);
  const userInfo: ResponseBusinesssDto = useAppSelector((state) => state.auth.userInfo);
  const location = useLocation();
  const search = new URLSearchParams(location.search);
  const firstId: number | null = search.get('firstId') ? parseInt(search.get('firstId')!) : null;
  const goodId: number | null = search.get('goodId') ? parseInt(search.get('goodId')!) : null;

  useEffect(() => {
    const fetchData = async () => {
      if (firstId != null && goodId != null) {
        const res: ResponseApiDto = await commentApi.getSingleComment(goodId, firstId);
        if (res.status >= 0 && res.data) {
          setComments(() => {
            let temp = [...comments];
            temp.unshift(res.data);
            return temp;
          });
        }
      }
    };
    fetchData();
  }, []);

  const loadMore = async () => {
    const res = await commentApi.getCommentPagination(page, limit, goodId!, firstId!);
    if (res.status >= 0) {
      setComments((prev) => [...prev, ...res.data.data]); // 使用函数式更新
      setPage((prev) => prev + 1);
      if (res.data.data.length < limit) {
        setFinish(true);
      }
    }
  };

  const refresh = async () => {
    const res = await commentApi.getCommentPagination(1, limit, goodId!);
    if (res.status >= 0) {
      setComments((prev) => [...res.data.data]); // 使用函数式更新
      if (res.data.data.length < limit) {
        setFinish(true);
      }
    }
  };

  const add = async (data: CommentAddProps) => {
    const formData = new FormData();
    formData.append('content', data.content);
    formData.append('mainCommentId', data.commentId.toString());
    formData.append('commentId', data.commentId.toString());
    Toast.loading('提交中...');
    const res = await commentApi.addComment2(formData);
    if (res.status >= 0) {
      Toast.success('回复成功');
      setComments((prev) => {
        let temp = [...prev];
        temp
          .find((d) => d.id === data.commentId)
          ?.replays.unshift({
            content: data.content,
            accountName: userInfo.name,
            accountAvatar: userInfo.avatar ?? '',
            commentAccountName: data.commentAccountName,
            mainCommentId: data.commentId,
            commentId: data.commentId,
          } as any);
        return temp;
      });
    } else {
      Toast.fail('回复失败');
    }
  };

  return (
    <>
      <CommentComponent
        comments={comments}
        finish={finish}
        onLoad={loadMore}
        onRefresh={refresh}
        onAdd={add}
      />
    </>
  );
};

export default Comments;
